package com.wwwc.index.servlet;

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.ServletRequestWrapper;
import java.net.*;

import java.rmi.RemoteException;

import com.wwwc.util.web.*;
import com.wwwc.index.ejb.EJBManager;
import com.wwwc.index.ejb.user.*;

public class UserInfoServlet extends HttpServlet {
    private User ejbdb;

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    {
	try {
	    response.setContentType("text/html");
	    PrintWriter out     = response.getWriter();
	    HttpSession session = request.getSession(true);
	    String user_ip      = request.getRemoteAddr();
	    String call_path    = request.getContextPath()+request.getServletPath();

	    String lid = (String)session.getAttribute("SelectedLanguageId");
	    if(lid == null) {
		System.out.println("UserInfoServlet:Error:lid==null");
		return;
	    }

	    Hashtable mhs = (Hashtable)session.getAttribute("LanguageHash_"+lid);
	    if(mhs == null) {
		System.out.println("UserInfoServlet:Error:101");
		return;
	    }

	    if(ejbdb == null) {
		ejbdb = (User)EJBManager.getEJB("java:comp/env/ejb/UserEJB", "User");
	    }

	    int count = 0;	
   	
	    String target_context = (String)request.getAttribute("TargetPageContext");
	    String target_link    = (String)request.getAttribute("TargetPageLink");
 
	    String UserInfoServletAction = request.getParameter("UserInfoServletAction");

	    if(UserInfoServletAction == null) {
		String login_message = (String)request.getAttribute("LoginMessage");
		UserProfile uf = (UserProfile)session.getAttribute("UserProfile");
		if(uf != null) {
		    out.println("<TABLE width=100%><TR><TD align=center><BR>Welcome:"+uf.getUserName()+"!</TD></TR></TABLE>");
		    return;
		}

		out.println(MyJavaScript.disableHistory());
		if(session.getAttribute("count") == null) {
		    session.setAttribute("count", ""+count);
		}
		else {
		    count = Integer.parseInt((String)session.getAttribute("count"));
		}

		if(count < 10) {
		    out.println("<BR>"+getLoginForm(login_message, false, session.getId(), call_path, user_ip)+"<BR>");
		}
		else {
		    out.println("<CENTER><h3>You have been locked out</h3></CENTER>");
		}
	    }
	    
	    if(UserInfoServletAction != null && UserInfoServletAction.equals("sign_in_check")) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String submit_id = request.getParameter("submit_id");

		if(!submit_id.equals(session.getId())) {
		    System.out.println("UserInfoServlet:Error:sign_in_check:submit_id="+submit_id+": sessionId="+session.getId());
		}

		if(!ejbdb.usernamePasswordCheck(username, password)) {
		    count = Integer.parseInt((String)session.getAttribute("count"));
		    session.setAttribute("count",""+(count+1));
		    if(count > 10) {
			out.println("<CENTER><h3>You have been locked out</h3></CENTER>");
			return;
		    }
		    
		    out.println("<BR>"+getLoginForm("<img src=/images/star.gif>Error!", true, 
						    session.getId(), call_path, user_ip)+"<BR>");
		}
		else {
		    UserProfile up = (UserProfile)ejbdb.getUserProfile(username, password);
		    if(up == null) {
			out.println("user profile not found");
		    }
		    else {
			if(up.getAccountStatus()== null || !up.getAccountStatus().equals("Actived")) {
			    out.println(activationMessage());
			}
			else {
			    session.setAttribute("UserProfile", up);
			    // reset directory
			    CategoryDetails cd = (CategoryDetails)session.getAttribute("SelectedCategory");
			    if(cd == null) {
				System.out.println("DirctroryServlet:Error:SelectedCategory==null");
				return;
			    }

			    String cid = ""+cd.getCategoryId();
			    String directory_table_name = cd.getDirectoryTableName();
			    
			    if(!lid.equals("en")) {
				directory_table_name = directory_table_name+"_"+lid.toUpperCase();
			    }

			    session.setAttribute("DirectoryListVector_"+directory_table_name, null);
			 
			    DirectoryDetails dd = (DirectoryDetails)session.getAttribute("LastDirectoryDetails_"+lid);
			    if(dd != null) {
				session.setAttribute("DirectorySelectedMid_"+lid, dd.getId());
			    }

			    out.println("\n<SCRIPT>");
			    out.println("\n\t top.location.replace(\""+call_path+"\");");
			    out.println("\n</SCRIPT>");
			}
		    }
		}
		return;
	    }
	    
	    //================================================
	    // e-mail password
	    //================================================

	    if(UserInfoServletAction != null && UserInfoServletAction.equals("forgot_pass")) {
		out.println(MyJavaScript.disableHistory());
		out.println(emailUserProfile(request, session, call_path));
	    }
	    
	    //================================================
	    // sign off
	    //================================================

	    if(UserInfoServletAction != null && UserInfoServletAction.equals("sign_off")) {
		session.invalidate();
		session = request.getSession(true);
		session.setAttribute("SelectedLanguageId", lid);
		out.println("\n<SCRIPT>");
		out.println("\n\t top.location.replace(\""+call_path+"\");");
		out.println("\n</SCRIPT>");
	    }
	}
	catch(IOException e) {
	    System.out.println("TopBarServlet:Error:401:"+e);
	    return;
	}
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
	doPost(request, response);
    }

    private StringBuffer getLoginForm(String message, boolean show_forgot, String submit_id, String call_path, String user_ip) {
	StringBuffer sbf = new StringBuffer();
	sbf.append("\n<FORM method='post' name='signInForm' action='"+call_path+"'>");
	sbf.append("\n<TABLE align=center cellSpacing=0 cellPadding=5 border=1>");
	if(message != null && message.length()>0) {
	    sbf.append("\n<TR>");
	    sbf.append("\n<TD align='center' colspan=5>"+message+"</TD></TR>");
	}
	sbf.append("\n<TR>");
	sbf.append("\n<TD align='center'>Username:</TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("<input type='text' name='username' value='William' size='21' maxlength='20'></TD>");
	sbf.append("\n<TD align='center'>Password:</TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("\n<input type='password' name='password' value='li0577' size='21' maxlength='20')></TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("\n<A href=javascript:document.signInForm.submit();>Sign In</A></TD>");
	sbf.append("\n<input type='hidden' name='UserInfoServletAction' value='sign_in_check'>");
	sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	sbf.append("\n</TD></TR></TABLE>");
	sbf.append("\n</FORM>");

	sbf.append("\n<FORM method='post' name='signInForm1' action='"+call_path+"'>");
	sbf.append("\n<TABLE align=center cellSpacing=0 cellPadding=5 border=1>");
	sbf.append("\n<TR>");
	sbf.append("\n<TD align='center'>Username:</TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("<input type='text' name='username' value='James-Lee' size='21' maxlength='20'></TD>");
	sbf.append("\n<TD align='center'>Password:</TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("\n<input type='password' name='password' value='li0578' size='21' maxlength='20')></TD>");
	sbf.append("\n<TD align='center'>");
	sbf.append("\n<A href=javascript:document.signInForm1.submit();>Sign In</A></TD>");
	sbf.append("\n<input type='hidden' name='UserInfoServletAction' value='sign_in_check'>");
	sbf.append("\n<input type='hidden' name='submit_id' value='"+submit_id+"'>");
	sbf.append("\n</TD></TR></TABLE>");
	sbf.append("\n</FORM>");

	if(show_forgot) {
	    sbf.append("\n<FORM method='post' action='"+call_path+"'>");
	    sbf.append("\n<TABLE align=center>");
	    sbf.append("\n<TR><TD align='center'>");
	    sbf.append("\n<TD align='left'>");
	    sbf.append("\n<input type='image' src='/images/forgot_passwd.gif' border='0'></TD>");
	    sbf.append("\n<input type='hidden' name='UserInfoServletAction' value='forgot_pass'>");
	    sbf.append("\n</TD></TR></TABLE>");
	    sbf.append("\n</FORM>");
	}
	return sbf;
    }

    private StringBuffer activationMessage() 
    {
	StringBuffer sb = new StringBuffer ();
	sb.append("\n<TABLE cellSpacing=0 cellPadding=0 border=0 width=100% style='font-size: 8pt' height=70>");
	sb.append("\n<TR><TD align=center style='font-size: 12pt'>");
	sb.append("\n<img src=/images/star.gif>Activation is required! ");
	sb.append("\n<BR>A verification link and code has been sent to your e-mail.");
	sb.append("\n</TD></TR></TABLE>");
	return sb;
    }

    private StringBuffer emailUserProfile(HttpServletRequest request, HttpSession session, String call_path) {
	String email   = request.getParameter("email");
	String form_id = request.getParameter("form_id");

	StringBuffer error = null;
	StringBuffer sbf   = new StringBuffer();

	if(email != null && form_id != null) {	  
	    MyUserInputCheck ck = new MyUserInputCheck();
	    if(!ck.checkEmail(email)) {
		error = new StringBuffer("E-mail format error!");
	    }

	    if(error == null) {
		if(!form_id.equals(session.getId())) {
		    System.out.println("TopBarBean:Error:form_id <> session id");
		    return null;
		}
	    }

	    if(error == null) {
		try {
		    if(ejbdb == null) {
			ejbdb = (User)EJBManager.getEJB("java:comp/env/ejb/UserEJB", "User");
		    }

		    ArrayList a = ejbdb.getUserProfileByEmail(email);
		    if(a == null || a.isEmpty()) {
			error = new StringBuffer("System can not find your record.");
		    }  

		    if(error == null) {
			UserProfile up = null;
			StringBuffer email_sbf = new StringBuffer();

			Iterator it = a.iterator();
			while(it.hasNext()) {
			    up = (UserProfile)it.next();
			    email_sbf.append("   Account Information\n");
			    email_sbf.append("===================================\n");
			    email_sbf.append("Username :\t"+up.getUserName()+"\n");
			    email_sbf.append("Password :\t"+up.getUserPassword()+"\n");
			    email_sbf.append("Access Level :\t"+up.getUserLevel()+"\n");
			    email_sbf.append("===================================\n");
			}
			
			email_sbf.append("\n\n-- 3WCenter.com\n"+(new Date()));
			
			String from     = "Services@3WCenter.com";
			String euser    = "Verification";
			String epass    = "LiNguyen5788";
			String subject  = "3WCenter.com Account Information";        

			try {
			    SendMail smail = new SendMail();
			    if(!smail.send(from, euser, epass, email, subject, email_sbf.toString())) {
				error = new StringBuffer("Sendding E-mail Error. Please try again later.");
			    }
			    else {
				sbf.append("<CENTER><BR/><H3>Your account information has been sent to: </H3>");
				sbf.append("<BR><BR>"+email+".</CENTER>");
				return sbf;
			    }
			}
			catch (Exception e) {
			    error = new StringBuffer("Sendding E-mail Error. Please try again later.");
			}  
		    }
		}
		catch (Exception e) {
		    error = new StringBuffer("Error. Please try again later.");
		    System.out.println("UserInfoServlet:emailUserInfo:Error:"+e);
		}
	    }
	}

	form_id = session.getId();

	sbf.append("<BR><BR>");

	if(error != null) {
	    sbf.append("<CENTER><img src='/images/star.gif' border='0'><I>"+error+"</I></CENTER>");
	}
 
	sbf.append("\n<FORM name='getUserInfoForm' method='post' action='"+call_path+"'>");
	sbf.append("\n<TABLE align='center' cellSpacing='0' cellPadding='5' border='1'>");
	sbf.append("\n<TR>");
	sbf.append("\n<TD align='right'><B>E-mail:</B></TD>");
	sbf.append("\n<TD align='center'><input type='text' name='email' value='' size='30' maxlength='50'></TD>");
	sbf.append("<TD><A href='javaScript:document.getUserInfoForm.submit();'><B>Submit</B></A></TD>");
	sbf.append("\n</TR>");
	sbf.append("\n</TABLE>");
	sbf.append("\n<input type='hidden' name='UserInfoServletAction' value='forgot_pass'>");
	sbf.append("\n<input type='hidden' name='form_id' value='"+form_id+"'>");
	sbf.append("\n</FORM>");
	return sbf;
    }
}






